<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use common\library\traits\APITrait;
use common\commands\VtCommon;

/**
 * Admin model
 */
class Admin extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;

    use APITrait;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%admin}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [];
    }

    /**
     * 返回字段限制
     * @return array
     */
    public function fields()
    {
        $fields = parent::fields();

        // 删除一些包含敏感信息的字段
        unset($fields['api_token_expire'], $fields['api_token'], $fields['password']);

        return $fields;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    public static function response($data)
    {
        header('Content-Type: application/json; charset=' . Yii::$app->charset);
        exit(json_encode($data));
    }

    /**
     * token验证
     * @param mixed $token
     * @param null $type
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        if (!static::apiTokenIsValid($token)) {
            return static::response(VtCommon::getPackedResponse(TOKEN_FAILED, Yii::t('app', 'TOKEN_FAILED'), null));
        }

        return static::findOne(['api_token' => $token, 'status' => self::STATUS_ACTIVE]);
    }

    public static function checkUserType($username)
    {
        if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     * @param $password
     * @throws \yii\base\Exception
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }


    /**
     * 检验apiToken是否有效
     * @param $token
     * @return bool
     */
    public static function apiTokenIsValid($token)
    {
        if (empty($token)) {//如果token为空
            return false;
        }

        $user = static::findOne(['api_token' => $token, 'status' => self::STATUS_ACTIVE]);//获取当前登录人信息
        if (empty($user)) {
            return false;
        }

        $apiTokenExpire = $user->api_token_expire;
        $expire = Yii::$app->params['user.apiTokenExpire'];

        if ($apiTokenExpire < time()) {//判断是否过期，如果过期时间戳小于当前时间戳  则为已经过期   如果过期时间戳大于当前时间戳则代表token还有效
            return false;
        } else {
            $newApiTokenExpire = time() + $expire;//新的过期时间
            $user->api_token_expire = $newApiTokenExpire;
            $user->last_ip = Yii::$app->request->getUserIP();
            $user->save();

            return true;
        }

    }
}
